package com.panfeng.xcloud.scheduler.jobs;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.panfeng.xcloud.common.core.utils.StringUtils;
import com.panfeng.xcloud.scheduler.constants.LockContants;
import com.panfeng.xcloud.scheduler.lock.RedisLock;
import com.panfeng.xcloud.scheduler.service.IDailyService;
import com.panfeng.xcloud.scheduler.service.IFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class DailySimpleJob extends BaseSimpleJob {

    @Autowired
    private RedisLock redisLock;

    @Autowired
    private IDailyService dailyService;

    @Autowired
    private IFeignService feignService;

    @Override
    protected void doJob(ShardingContext shardingContext) {
        String lockKey = LockContants.XDCLOUD_LOCK_DAILY;
        String expireAfterTime = String.valueOf(System.currentTimeMillis() + 10000);
        boolean lock = redisLock.lock(lockKey, expireAfterTime);
        log.info(">>> DailySimpleJob-是否获取到锁:{} <<<", lock);
        try {
            if (lock) {
                dailyService.daily();
            } else {
                log.info(">>> DailySimpleJob-没有获取到锁，不执行任务!");
            }
        } catch (Exception e) {
            log.error(">>> DailySimpleJob 每日任务-任务异常", e);
            feignService.sendEmail(">>> DailySimpleJob 每日任务-任务异常 <<<" + StringUtils.printStackTraceToString(e));
        } finally {
            if (lock) {
                redisLock.unlock(lockKey, expireAfterTime);
                log.info(">>> DailySimpleJob 每日任务-任务结束，释放锁 <<<");
            } else {
                log.info(">>> DailySimpleJob 每日任务-没有获取到锁，无需释放锁 <<<");
            }
        }
    }

}
